package com.sky.service.impl;

import ch.qos.logback.core.rolling.helper.IntegerTokenConverter;
import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.WorkspaceService;
import com.sky.utils.JwtUtil;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    public TurnoverReportVO getturnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList){
            //获取指定日期的时分秒
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status",5);
            Double turnover = orderMapper.sumByMap(map);
            if (turnover == null) {
                turnover = 0.0;
            }
            turnoverList.add(turnover);
        }
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(StringUtil.join(",", dateList));
        turnoverReportVO.setTurnoverList(StringUtil.join(",", turnoverList));
        return turnoverReportVO;
    }

    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //获取日期列表
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            //往后增加天数，直到到end结束
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //计算每天新增的用户数量
        List<Integer> newUserList = new ArrayList<>();
        //计算每天的总的用户数量
        List<Integer> totalUserList = new ArrayList<>();
        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("end",endTime);
            Integer  totalUser =userMapper.countByMap(map);
            totalUserList.add(totalUser);
            map.put("begin",beginTime);
           newUserList.add(userMapper.countByMap(map));
        }
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(StringUtil.join(",", dateList));
        userReportVO.setNewUserList(StringUtil.join(",", newUserList));
        userReportVO.setTotalUserList(StringUtil.join(",", totalUserList));
        return userReportVO;
    }

    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            //往后增加天数，直到到end结束
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //获取订单总数
        List<Integer> orderCountList = new ArrayList<>();
        //获取有效订单总数
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList)
        {
            //查询每天订单总数
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天的有效订单数
            Integer validOrderCount = getOrderCount(beginTime, endTime, 5);
            //查询每天订单总数
            Integer totalOrderCount = getOrderCount(beginTime, endTime, null);
            validOrderCountList.add(validOrderCount);
            orderCountList.add(totalOrderCount);
        }
        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(StringUtil.join(",", dateList));
        orderReportVO.setOrderCountList(StringUtil.join(",", orderCountList));
        orderReportVO.setValidOrderCountList(StringUtil.join(",", validOrderCountList));
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        orderReportVO.setTotalOrderCount(totalOrderCount);
        orderReportVO.setValidOrderCount(validOrderCountList.stream().reduce(Integer::sum).get());
        orderReportVO.setOrderCompletionRate(orderReportVO.getValidOrderCount() * 1.0 / orderReportVO.getTotalOrderCount());
        return orderReportVO;
    }
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        //获得有效订单数量
        return orderMapper.countByMap(map);
    }
    //获取top10的菜单
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> list = orderMapper.getSalesTop10(beginTime, endTime);
        log.info("查询结果：{}", list);

        List<String> nameList =list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers=list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(StringUtil.join(",", nameList));
        salesTop10ReportVO.setNumberList(StringUtil.join(",", numbers));
        return salesTop10ReportVO;
    }
    //导出运营数据报表

    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN)
                , LocalDateTime.of(end, LocalTime.MAX));
        //2.封装数据，写入Excel文件中
       InputStream in =this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try{
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            XSSFSheet sheet = workbook.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);

            XSSFRow row = sheet.getRow(3);
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(4).getCell(4).setCellValue(businessData.getValidOrderCount());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                BusinessDataVO businessDataOfDate = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));
                //获取每一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataOfDate.getTurnover());
                row.getCell(3).setCellValue(businessDataOfDate.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataOfDate.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataOfDate.getUnitPrice());
                row.getCell(6).setCellValue(businessDataOfDate.getNewUsers());
            }
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
